package com.wh.message.voice.service.impl;

import com.wh.common.util.Result;
import com.wh.message.utils.HttpPostUtil;
import com.wh.message.utils.ValidatorFactoryUtil;
import com.wh.message.voice.in.SmsEntityIn;
import com.wh.message.voice.service.ChuangLanSendVoiceService;
import com.wh.message.voice.utils.SmsConfig;
import com.wh.msg.ResultCode;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 创蓝语音短信发送
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.mongo.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class ChuangLanSendVoiceServiceImpl implements ChuangLanSendVoiceService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());



    @Value("#{settings['chuanglan.isOpen']}")
    public String isOpen ;

    private SmsConfig voiceConfig;

    public void setVoiceConfig(SmsConfig voiceConfig) {
        this.voiceConfig = voiceConfig;
    }

    @Override
    public Result sendVoice(SmsEntityIn in){
        logger.info("sendSms创蓝语音短信==============开始========");
        logger.info("sendSms创蓝语音短信smsEntityIn={}", JSONObject.fromObject(in).toString());
        logger.info("sendSms创蓝语音短信voiceConfig={}",JSONObject.fromObject(voiceConfig).toString());
        Result res = new Result();
        try {
            res= ValidatorFactoryUtil.validate(in);
            if(!ResultCode.RES_OK.equals(res.getResCode())){
                logger.info("sendSms创蓝语音短信，参数校验不通过,result={}",res);
                return res;
            }
            HttpPostUtil hpu = new HttpPostUtil();
            String phone = in.getPhoneName();
            phone.replaceAll(";", ",");
            in.setPhoneName(phone);
            // 时间戳
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timestamp = sdf.format(new Date());

            String sig = DigestUtils.md5Hex(voiceConfig.getAutograph() + in.getPhoneName() + voiceConfig.getPassword() + timestamp);

            String str = "{\"voiceinfo\": {" +
                    "\"organization\":\"" + voiceConfig.getAccount() + "\"," +
                    "\"timestamp\":\"" + timestamp + "\"," +
                    "\"shownum\":\"" + voiceConfig.getSpeechPhone() + "\"," +
                    "\"phonenum\":\"" + in.getPhoneName() + "\"," +
                    "\"content\":\"" + sig + "\"," +
                    "\"vfcode\":\"" + in.getContent() + "\"," +
                    "\"playnum\":" + voiceConfig.getNeedstatus() + "," +
                    "\"ivrfileid\":''" +
                    "}" +
                    "}";

            // 提交请求
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("method", "vcfplay");
            map.put("voiceinfo", str);
            String result = null;
            JSONObject json = null;
            if (!Boolean.parseBoolean(isOpen)) {
                result = "{code:\"0\",msg:\"发送成功\"}";
            } else {
                try {
                    result = hpu.httpPost(voiceConfig.getSmsUrl(), map);
                } catch (Exception e) {
                    logger.error("sendVoice发送语音短信异常");
                    e.printStackTrace();
                    res.setResCode(ResultCode.RES_ERR);
                }
            }

            json = JSONObject.fromObject(result);
            if (null != json && "0".equals(json.getString("code"))) {
                res.setResCode(ResultCode.RES_OK);
            } else {
                res.setResCode(ResultCode.RES_NO);
            }
            json.put("content", in.getContent());
            json.put("phoneName", in.getPhoneName());
        }catch (Exception e){
            logger.error("sendSms创蓝语音短信============出现异常msg={}",e.getMessage());
            e.printStackTrace();
            res.setResCode(ResultCode.RES_ERR);
            res.setResult(e.getMessage());
        }
            logger.info("sendSms创蓝语音短信==============结束========");
            return res;
    }





}
